package cn.skcks.shirospringboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Controller
public class MyController {

	@GetMapping(value = {"/","/index"})
	public String toIndex(Model model){

		model.addAttribute("msg","Hello World");

		return "index";
	}

	@GetMapping("/user/add")
	public String add(){
		return "user/add";
	}

	@GetMapping("/user/delete")
	public String delete(){
		return "user/delete";
	}

	@GetMapping("/user/list")
	public String list(){
		return "user/list";
	}

	@GetMapping("/user/update")
	public String update(){
		return "user/update";
	}

	@GetMapping("/login")
	public String toLogin(){
		return "login";
	}

	@PostMapping("/login")
	public String login(String user,String pwd,Model model){
		// 获取 当前用户实例
		Subject subject = SecurityUtils.getSubject();
		// 获取 用户登录数据
		AuthenticationToken authenticationToken = new UsernamePasswordToken(user, pwd);
		// 执行登录方法
		try {
			subject.login(authenticationToken);

			Session session = subject.getSession();
			session.setAttribute("login",true);

			return "redirect:index";
		} catch (UnknownAccountException e){
			model.addAttribute("error","用户名不存在");
			return "login";
		} catch (IncorrectCredentialsException e){
			model.addAttribute("error","认证失败");
			return "login";
		}catch (AuthenticationException e) {
			model.addAttribute("error",e.getMessage());
			return "login";
		}
	}

	@GetMapping("/logout")
	public String logout(){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();

		Session session = subject.getSession();
		session.setAttribute("login",null);

		return "logout";
	}

	@RequestMapping("/unauthorized")
	@ResponseBody
	public String unauthorized(HttpServletResponse response){
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		return "401 未经授权的访问!";
	}
}